package com.lanmaoly.demo;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class LockTest {

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 20, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), new NamedThreadFactory("split-file"), new ThreadPoolExecutor.CallerRunsPolicy());
        String id = "123123123";

        for (int i = 0; i < 10; i++) {
            executor.execute(() -> {
                try {
                    print(id);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        for (int i = 0; i < 10; i++) {
            executor.execute(() -> {
                try {
                    print2(id);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
    }

    private static void print(String id) throws InterruptedException {
        synchronized (id) {
            System.out.println("1:" + Thread.currentThread().getName() + ":" + id);
            Thread.sleep(2000);
        }
    }

    private static void print2(String id) throws InterruptedException {
        synchronized (id) {
            System.out.println("2:" + Thread.currentThread().getName() + ":" + id);
            Thread.sleep(2000);
        }
    }
}
